package com.itic.mall.mobile.login;



import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.users.userscode.persistence.model.UsersCode;
import com.itic.mall.system.users.userscode.service.UsersCodeService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.userstoken.persistence.model.UsersToken;

/**
 * 登入模块接口信息
 * @author 许小宝
 * @time 2017/12/01
 */
@Controller
@RequestMapping(value="/mobile/login")
public class LoginInterface
     extends BaseMobileInterface {
	
	
	   @Autowired
       private UsersCodeService usersCodeService;
	  
	   /**
	    * APP手机发送验证码
	    * @return
	    */
	   @RequestMapping(value="/code")
	   @ResponseBody
	   public Map<String,Object> code( HttpServletRequest request,HttpServletResponse response, String phone ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(phone) ){
		   		    //发送验证码
	   				String randomNumStr = RandomStringHelper.randomNumStr(6);
	   				
	   				UsersCode phoneCode = new UsersCode();
	   				phoneCode.setPhone(phone);
	   				phoneCode.setCode(randomNumStr);
	   				phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
	   				
	   				String temp = usersCodeService.add(phoneCode);
	   				String sendMassage = sendMassage(phone, randomNumStr);
	   				  
	   				if( SUCCESS.equals(temp) && SUCCESS.equals(sendMassage) ){
	   					errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
	   				}else{
	   					errorCode = FAIL_CODE_ERROR_CODE;
				       	errorMsg = FAIL_CODE_ERROR_MSG;
	   				}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("LoginInterface", "code", e.toString(),"APP手机发送验证码",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	
	   /**
	    * APP用户注册
	    * @return
	    */
	   @RequestMapping(value="/reg")
	   @ResponseBody
	   public Map<String,Object> reg( HttpServletRequest request,HttpServletResponse response,UsersMall user,String code ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		//判断参数是否有效
		   		if( StringHelper.isNotBlank(user.getUserPhone()) && StringHelper.isNotBlank(code) && StringHelper.isNotBlank(user.getUserPwd()) ){
		   			//判断手机号码是否注册过
		   			UsersMall usersTemp = usersMallService.getByPhone(user.getUserPhone());
		   			if( null == usersTemp ){
		   				//验证码是否有效code
		   				if( isEffectiveCode(user.getUserPhone(),code) ){
		   					user.setType("001");
				   			user.setLaiyuan("app");
				   			usersMallService.reg(user);
				   			errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{
					   		errorCode = PHONE_CODE_ERROR_CODE;
					       	errorMsg = PHONE_CODE_ERROR_MSG;
		   				}
		   			}else{
		   		     	//提示用户号码已注册过了
		   				errorCode = PHONE_REGED_ERROR_CODE;
				       	errorMsg = PHONE_REGED_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("LoginInterface", "reg", e.toString(),"APP用户注册",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	    
	   /**
	    * APP用户登入
	    * @return
	    */
	   @RequestMapping(value="/in")
	   @ResponseBody
	   public Map<String,Object> list( HttpServletRequest request,HttpServletResponse response,String phone, String pwd, String code,String token,String appId,String unionid, String openid , String yunId ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	String isStore = DBConst.FALSE;//是否为云店主，默认不是
		   	try{
		   		Map<String, Object> dataMap = new HashMap<String,Object>();
		   		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){//用户TOKEN与设备ID登入
		   			UsersToken usersToken = getTokenByTokenAndAppId(token, appId);
		   			if( null != usersToken ){
		   				//是否异地登入
		   				if( DBConst.FALSE.equals(usersToken.getIsOffsite()) ){
		   					
			   				UsersMall usersMall = usersMallService.get(usersToken.getUserId());
			   				if( null != usersMall && "002".equals(usersMall.getType()) ){
			   					isStore = DBConst.TRUE;
			   				}
			   				dataMap.put("token", usersToken.getAccessToken());
			   				dataMap.put("expiredTime", usersToken.getExpiredTime());
			   				dataMap.put("userid", usersMall.getId());
			   				if(usersMall.getUnionid()!=null && usersMall.getUnionid().length()>0)
			   					dataMap.put("isBind","1");
			   				else
			   					dataMap.put("isBind", "0");
			   				resultMap.put(DATA, dataMap);
			   				errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{
		   					errorCode = OFF_SITE_ERROR_CODE;
					       	errorMsg = OFF_SITE_ERROR_MSG;
		   				}
		   			}else{
		   				errorCode = LOGIN_ERROR_CODE;
				       	errorMsg = LOGIN_ERROR_MSG;
		   			}
		   		}else if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) && StringHelper.isNotBlank(appId) ){//手机号码与动态验证码登入
		   			if( isEffectiveCode(phone, code) ){
		   				UsersMall usersMall = getUsersByPhone(phone);
		   				if( null != usersMall ){
		   					UsersToken usersToken = createToken(usersMall, appId);
		   					//同步数据库
		   					usersTokenService.addAndSyncOther(usersToken);
		   					if( null != usersMall && "002".equals(usersMall.getType()) ){
			   					isStore = DBConst.TRUE;
			   				}
		   					dataMap.put("token", usersToken.getAccessToken());
			   				dataMap.put("expiredTime", usersToken.getExpiredTime());
			   				dataMap.put("userid", usersMall.getId());
			   				if(usersMall.getUnionid()!=null && usersMall.getUnionid().length()>0)
			   					dataMap.put("isBind","1");
			   				else
			   					dataMap.put("isBing", "0");
			   				resultMap.put(DATA, dataMap);
			   				errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{//用户未找到
		   				    //注册手机号码
		   					UsersMall user = new UsersMall();
		   					user.setUserPhone(phone);
		   					user.setLaiyuan("APP");
		   			 		usersMall = usersMallService.reg(user);
			   			 	UsersToken usersToken = createToken(usersMall, appId);
		   					//同步数据库
		   					usersTokenService.addAndSyncOther(usersToken);
		   					if( null != usersMall && "002".equals(usersMall.getType()) ){
			   					isStore = DBConst.TRUE;
			   				}
		   					dataMap.put("token", usersToken.getAccessToken());
			   				dataMap.put("expiredTime", usersToken.getExpiredTime());
			   				dataMap.put("userid", usersMall.getId());
			   				if(usersMall.getUnionid()!=null && usersMall.getUnionid().length()>0)
			   					dataMap.put("isBind","1");
			   				else
			   					dataMap.put("isBing", "0");
			   				resultMap.put(DATA, dataMap);
					   		errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}
		   			}else{//手机号码与验证码不匹配
		   				errorCode = PHONE_CODE_ERROR_CODE;
				       	errorMsg = PHONE_CODE_ERROR_MSG;
		   			}
		   		}else if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(pwd) && StringHelper.isNotBlank(appId) ){//手机号码与密码登入
		   			UsersMall usersMall = getUsersByPhone(phone);
		   			if( null != usersMall ){
		   				if( pwd.equals(usersMall.getUserPwd()) ){
		   					UsersToken usersToken = createToken(usersMall, appId);
		   					//同步数据库
		   					usersTokenService.addAndSyncOther(usersToken);
		   					if( null != usersMall && "002".equals(usersMall.getType()) ){
			   					isStore = DBConst.TRUE;
			   				}
		   					dataMap.put("token", usersToken.getAccessToken());
			   				dataMap.put("expiredTime", usersToken.getExpiredTime());
			   				dataMap.put("userid", usersMall.getId());
			   				if(usersMall.getUnionid()!=null && usersMall.getUnionid().length()>0)
			   					dataMap.put("isBind","1");
			   				else
			   					dataMap.put("isBing", "0");
			   				resultMap.put(DATA, dataMap);
			   				errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{
		   					errorCode = PWD_ERROR_CODE;
					       	errorMsg = PWD_ERROR_MSG;
		   				}
	   				}else{//用户未找到
	   					errorCode = PHONE_NULL_ERROR_CODE;
				       	errorMsg = PHONE_NULL_ERROR_MSG;
	   				}
		   		}else if( StringHelper.isNotBlank(unionid) && StringHelper.isNotBlank(appId) ){//微信授权唯一快捷登入
		   			UsersMall usersMall = getUsersByUnionid(unionid);
		   			if( null != usersMall && StringHelper.isNotBlank(usersMall.getUserPhone()) ){
		   			//if( null != usersMall ){
		   				UsersToken createToken = createToken(usersMall, appId);
		   		     	//同步数据库
	   					usersTokenService.addAndSyncOther(createToken);
	   					if( null != usersMall && "002".equals(usersMall.getType()) ){
		   					isStore = DBConst.TRUE;
		   				}
	   					dataMap.put("token", createToken.getAccessToken());
		   				dataMap.put("expiredTime", createToken.getExpiredTime());
		   				dataMap.put("userid", usersMall.getId());
		   				if(usersMall.getUnionid()!=null && usersMall.getUnionid().length()>0)
		   					dataMap.put("isBind","1");
		   				else
		   					dataMap.put("isBing", "0");
		   				resultMap.put(DATA, dataMap);
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = UNIONID_NULL_ERROR_CODE;
				       	errorMsg = UNIONID_NULL_ERROR_MSG;
		   			}
		   		}else if( StringHelper.isNotBlank(openid) && "gzh".equals(appId) ){ //公众号ID登入
		   			UsersMall usersMall = getUsersByOpenid(openid);
		   			if( null != usersMall ){
		   				UsersToken createToken = createToken(usersMall, appId);
		   		     	//同步数据库
	   					usersTokenService.add(createToken);
	   					if( null != usersMall && "002".equals(usersMall.getType()) ){
		   					isStore = DBConst.TRUE;
		   				}
	   					dataMap.put("token", createToken.getAccessToken());
		   				dataMap.put("expiredTime", createToken.getExpiredTime());
		   				dataMap.put("userid", usersMall.getId());
		   				if(usersMall.getUnionid()!=null && usersMall.getUnionid().length()>0)
		   					dataMap.put("isBind","1");
		   				else
		   					dataMap.put("isBing", "0");
		   				resultMap.put(DATA, dataMap);
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = OPENID_NULL_ERROR_CODE;
				       	errorMsg = OPENID_NULL_ERROR_MSG;
		   			}
		   		}else if( StringHelper.isNotBlank(yunId) ){
		   			UsersMall usersMall = usersMallService.get(yunId);
		   			if( null != usersMall ){
		   				UsersToken createToken = createToken(usersMall, appId);
		   		     	//同步数据库
	   					usersTokenService.add(createToken);
	   					if( null != usersMall && "002".equals(usersMall.getType()) ){
		   					isStore = DBConst.TRUE;
		   				}
	   					dataMap.put("token", createToken.getAccessToken());
		   				dataMap.put("expiredTime", createToken.getExpiredTime());
		   				dataMap.put("userid", usersMall.getId());
		   				if(usersMall.getUnionid()!=null && usersMall.getUnionid().length()>0)
		   					dataMap.put("isBind","1");
		   				else
		   					dataMap.put("isBing", "0");
		   				resultMap.put(DATA, dataMap);
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = YUNID_NULL_ERROR_CODE;
				       	errorMsg = YUNID_NULL_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("LoginInterface", "in", e.toString(),"APP用户登入",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	resultMap.put(IS_STORE, isStore);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	    
	  /**
	    * APP用户注册
	    * @return
	    */
	   @RequestMapping(value="/out")
	   @ResponseBody
	   public Map<String,Object> out( HttpServletRequest request,HttpServletResponse response,String token,String appId ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		//判断参数是否有效
		   		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
		   			UsersToken usersToken = getTokenByTokenAndAppId(token,appId);
		   			if( null != usersToken ){
		   				usersTokenService.delete(usersToken);
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = LOGIN_ERROR_CODE;
				       	errorMsg = LOGIN_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("LoginInterface", "out", e.toString(),"APP用户退出登入",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
    
	   
}